﻿using System.Data;
using System.Data.SqlClient;
using System.Linq;
using Citi.Helpers;

namespace Citi.SecurityHelper
{
    public static class SecureSqlConnection
    {
        public static void ExecuteNonQuery(string query, string connectionString, string sqlPwdFile, int timeout = 1000)
        {
            ExecuteInternalNonQuery(query, connectionString, sqlPwdFile, timeout);
        }

        internal static void ExecuteInternalNonQuery(string query, string connectionString, string sqlPwdFile, int timeout = 1000)
        {
            SqlHelper.ExecuteNonQuery(query, GetConnectionString(connectionString, sqlPwdFile), timeout);
        }

        public static DataTable ExecuteReader(string query, string connectionString, string sqlPwdFile, int timeout = 1000)
        {
            return ExecuteInternalReader(query, connectionString, sqlPwdFile, timeout);
        }

        internal static DataTable ExecuteInternalReader(string query, string connectionString, string sqlPwdFile, int timeout = 1000)
        {
            return SqlHelper.ExecuteReader(query, GetConnectionString(connectionString, sqlPwdFile), timeout);
        }

        internal static string GetConnectionString(string connectionString, string sqlPwdFile)
        {
            var password = CitiPasswordFile.GetDecryptedText(sqlPwdFile, SecurityConfigurations.RobotUserName, SecurityConfigurations.RobotPassword).FirstOrDefault();
            return string.Format(connectionString, password);
        }

        internal static SqlConnection GetSecureSqlConnection(string connectionString, string sqlPwdFile)
        {
            return new SqlConnection(GetConnectionString(connectionString, sqlPwdFile));
        }
    }
}
